<?php

namespace app\api\controller\user;

use app\api\controller\BaseController;
use app\models\store\StoreCoupon;
use app\models\user\UserBill;
use app\models\system\SystemPoint;
use app\models\user\User as UserModel;
use app\models\user\WechatUser;
use app\Request;
use EasyWeChat\Factory;
use Endroid\QrCode\QrCode;
use services\MiniProgramService;
use services\pay\WxPay;
use services\SystemConfigService;
use services\UtilService;
use app\models\store\StoreOrderCar;
use think\facade\Cache;
use think\facade\Db;
use utils\Json;

/**
 * 用户的信息接口
 * Class UserController
 * @package app\api\controller\user
 */
class UserController extends BaseController
{
    /**
     * 用户的信息的接口
     * @param Request $request
     * @return
     */
    public function userinfo(Request $request)
    {
        return app('json')->success($request->user()->toArray());
    }

    /**
     * 获取洗车的记录
     * @param Request $request
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cashLog(Request $request)
    {
        list($type, $limit, $page) = UtilService::getMore([
            ["type", ""],
            ["limit", ""],
            ["page", 1]
        ], $request, true);
        if (!$type) $type = "all";
        $where["data"] = $type;
        if ($type == "all") {   // 全部
            $list = UserBill::where("wxapp_id", $this->wxapp_id)->where("uid", $request->uid())
                ->where("is_pay", 1)
                ->field("id, title, type, number, balance, add_time")->page((int)$page, (int)$limit)->select();
            $count = UserBill::where("wxapp_id", $this->wxapp_id)->where("is_pay", 1)->where("uid", $request->uid())->count();
        } elseif ($type == "lately7") {
            $list = UserBill::where("wxapp_id", $this->wxapp_id)
                ->where("uid", $request->uid())
                ->where("is_pay", 1)
                ->where("add_time", "between", [strtotime("-7 day"), time()])
                ->field("id, title, type, number, balance, add_time")
                ->page((int)$page, (int)$limit)
                ->select();
            $count = UserBill::where("wxapp_id", $this->wxapp_id)
                ->where("add_time", "between", [strtotime("-7 day"), time()])
                ->where("is_pay", 1)
                ->count();
        } else {   // 本天
            $list = UserBill::where("uid", $request->uid())
                ->where("add_time", 'between', [strtotime(date("Y-m-d", time())), strtotime(date("Y-m-d", time())) + 86400])
                ->where("is_pay", 1)
                ->field("id, title, type, number, balance, add_time")
                ->page((int)$page, (int)$limit)
                ->select();
            $count = UserBill::where("uid", $request->uid())
                ->where("is_pay", 1)
                ->where("add_time", 'between', [strtotime(date("Y-m-d", time())), strtotime(date("Y-m-d", time())) + 86400])
                ->count();
        }
        foreach ($list as &$item) {
            $item["add_time"] = date("Y-m-d H:i:s", $item["add_time"]);
        }
        return app("json")->successful(compact("count", "list"));
    }

    /**
     * 套餐列表
     * @param Request $request
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function mealList(Request $request)
    {
        $list = SystemPoint::getSystemList();
        return app("json")->successful(compact("list"));
    }

    /**
     * 购买积分
     * @param Request $request
     * @return Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function buyPoint(Request $request)
    {
        if ($request->method() == "GET") {      // 获取请求的参数
            $meal_id = $request->get("meal_id");
            $where["wxapp_id"] = $this->wxapp_id;
            $where["id"] = $meal_id;
            $where["is_del"] = 0;
            $where["is_show"] = 1;
            $mealData = SystemPoint::get($where);
            if (!$mealData) return app("json")->fail("套餐不存在");  // 调用微信支付返回对应的数据

            // 新的接口的书写
            $wxoay = new WxPay([
                "app_id" => "wx686d9d1f3360b556",
                'app_secret' => '60e031c7e4443ea3bdbc0deca5b1639f',
                'mchid' => 1602484692,
                'apikey' => 'MBZNZBWHYXGS91420100MA49CAEY2Q20'
            ]);
            $title = '积分购买';
            $order_num = $this->createOrderNo();
            $data = [
                'uid' => $request->uid(),
                'pm' => 0,
                'title' => $title,
                'category' => 'integral',
                'type' => 2,
                'number' => $mealData["num"],
                'balance' => $mealData["price"],
                'wxapp_id' => $this->wxapp_id,
                'mark' => "备注",
                'add_time' => time(),
                'order_num' => $order_num,
                'link_id' => $meal_id
            ];
            $bill_id = Db::name("user_bill")->insertGetId($data);
            $request = $wxoay->unifiedorder($order_num, WechatUser::getOpenId($request->uid()), $mealData["price"], $title);
            $request['order_id'] = $bill_id;
            return app("json")->successful(compact('request'));

        } elseif ($request->method() == "POST") {   // 支付的回调
            $order_id = $request->post("order_id");
            if (UserBill::payOk($request->uid(), $order_id)) {
                return app("json")->successful("支付成功");
            } else {
                return app("json")->fail(UserBill::getErrorInfo() ?: "支付失败");
            }
        }
        return app("json")->fail("请求方式错误");
    }


    /**
     * 绑定手机号
     * @param Request $request
     */
    public function bindPhone(Request $request)
    {
        $param = $request->param();
        $post_cache_key = $param['cache_key'];
        $session_key = Cache::get('eb_api_code_' . $post_cache_key);
        $code = $param["code"];
        $userInfoCong = MiniProgramService::getUserInfo($code);
        $session_key = $userInfoCong['session_key'];
        $encryptedData = $param['encryptedData'];
        try {
            $data = MiniProgramService::encryptor($session_key, $param["iv"], $encryptedData);
        } catch (\Exception $exception) {
            if ($exception->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
        }
        if (!isset($data["phoneNumber"])) return app('json')->fail('获取手机号错误');
        $phone = $data["phoneNumber"];
        if (UserModel::where("uid", $request->uid())->save(["phone" => $phone]))
            return app('json')->successful('绑定手机号成功');
        else
            return app("json")->fail("绑定手机号失败");
    }

    /**
     * 产品反馈
     * @param Request $request
     */
    public function productOption(Request $request)
    {
        list($describe, $img) = UtilService::getMore([
            ['describe', ''],
            ['img', '']
        ], $request, true);
        if (!$describe) return app("json")->fail("请添加描述");
        $imgList = explode(',', $img);
        if (count($imgList) > 6) return app("json")->fail("图片数量超过限制");
        $opinoin_id = Db::name("user_opinion")->insertGetId([
            'uid' => $request->uid(),
            'describe' => $describe,
            'add_time' => time(),
            'wxapp_id' => $this->wxapp_id
        ]);
        if ($opinoin_id) {
            foreach ($imgList as $item) {
                Db::name("opinion_image")->where('id', $item)->update([
                    'opinion_id' => $opinoin_id
                ]);
            }
        } else {
            return app("json")->fail("评论失败");
        }
        return app("json")->successful("评论成功");
    }

    /**
     * 上传图片
     * @param Request $request
     */
    public function uploadFile(Request $request)
    {
        $file = $request->file("file");
        if (!$file) return app("json")->fail("请选择文件");
        $fileSize = $file->getSize();
        if ($fileSize > 2097152) return app("json")->fail("大小超过限制");
        $saveName = \think\facade\Filesystem::disk("public")->putFile("uploads", $file);
        if (!$saveName) return app("json")->fail("文件上传失败");
        // 将文件保存起来
        $fullName = $_SERVER["SERVER_NAME"] . "/uploads/" . $saveName;
    }

    /**
     * 积分日志
     * @param Request $request
     * @return Json
     */
    public function pointLog(Request $request)
    {
        $list = Db::name("user_point_log")
            ->where("uid", $request->uid())
            ->where("wxapp_id", $this->wxapp_id)
            ->order("add_time DESC")
            ->paginate(15)->each(function ($item, $key) {
                $item["add_time"] = date("Y-m-d H:i:s", $item["add_time"]);
                return $item;
            });
        return app("json")->successful(compact("list"));
    }

    /**
     * 购买洗车券
     * @param Request $request
     */
    public function buyCoupon(Request $request)
    {
        if ($request->method() == "GET") {
            // 查询是否存在这张优惠券
            $param = $request->param();
            if (!isset($param["coupon_id"]) || empty($param['coupon_id'])) return app("json")->fail("请传入优惠券的ID");
            $couponData = StoreCoupon::where('is_del', 0)->where("id", $param["coupon_id"])
                ->find();
            if (!$couponData) return app("json")->fail("优惠券不存在");
            // 获取一些参数
            $wxConfig = SystemConfigService::more(['routine_appId', 'routine_appsecret', 'pay_weixin_mchid', 'pay_weixin_key']);
            $wxpay = new WxPay([
                "app_id" => $wxConfig['routine_appId'],
                'app_secret' => $wxConfig['routine_appsecret'],
                'mchid' => $wxConfig['pay_weixin_mchid'],
                'apikey' => $wxConfig['pay_weixin_key']
            ]);
            $title = '购买洗车券';
            $orderNum = $this->createOrderNo();
            $data = [
                'uid' => $request->uid(),
                'pm' => 0,
                'title' => $title,
                'category' => 'now_money',
                'type' => 3,
                'number' => $param['cup_num'],
                'balance' => $couponData["price"] * $orderNum,
                'wxapp_id' => $this->wxapp_id,
                'mark' => '购买洗车券',
                'add_time' => time(),
                'order_num' => $orderNum,
                'link_id' => $param['coupon_id'],
            ];
            $bill_id = Db::name('user_bill')->insertGetId($data);
            $result = $wxpay->unifiedorder(
                $orderNum,
                WechatUser::getOpenId($request->uid()),
                $couponData["price"] * $orderNum,
                $title
            );
            $result["order_id"] = $bill_id;
            return app("json")->successful(compact('result'));
        } elseif ($request->method() == "POST") {   // 回调
            $order_id = $request->post("order_id");
            if (UserBill::buyCoupon($request->uid(), $order_id)) {
                return app("json")->successful("购买成功");
            }
            return app("json")->fail("购买优惠券失败");
        } else {
            return app("json")->fail("请求方式错误");
        }
    }


    /**
     * 获取又回去拿的数据
     * @param Request $request
     * @param $coupon_id integer 优惠券的ID
     */
    public function couponData(Request $request, $coupon_id = 0)
    {
        if (!$coupon_id) return app("json")->fail('请传入的ID');
        $couponData = StoreCoupon::where('is_del', 0)
            ->field('title, coupon_time, add_time, price, num')
            ->order("sort DESC")
            ->where("id", $coupon_id)
            ->find();
        if (!$couponData) return app("json")->fail("优惠券不存在");
        return app("json")->successful(compact('couponData'));
    }


    /**
     * 判断优惠券是否被领取
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isReceive(Request $request)
    {
        $param = $request->param();
        $send_id = $param["send_id"];
        $coupon_id = $param["coupon_id"];
        $coupon_Data = Db::name("store_coupon_user")->where("id", $coupon_id)->find();
        $data = array();
        if ($coupon_Data["uid"] != $send_id) {
            $data["flag"] = true;
            return app("json")->fail(compact("data"));
        }
        $data["flag"] = false;
        return app("json")->successful("正常展示", compact("data"));
    }


    /**
     * 领取优惠券
     * @param Request $request
     */
    public function receiveCoupon(Request $request)
    {
        $param = $request->param();
        $rev_id = $request->uid();
        $send_id = $param["send_id"];
        $coupon_id = $param["coupon_id"];
        $coupon_Data = Db::name("store_coupon_user")->where("id", $coupon_id)->find();
        if ($coupon_Data["status"] == 1) {
            return app("json")->fail("优惠券已被使用");
        }
        if ($coupon_Data["status"] == 2) {
            return app("json")->fail("优惠券已过期");
        }
        if ($coupon_Data["end_time"] <= time()) {
            return app("json")->fail("优惠券已过期");
        }
        if ($coupon_Data["use_time"] != 0) {
            return app("json")->fail("优惠券已被使用");
        }
        if ($coupon_Data["uid"] != $send_id) {
            return app("json")->fail("优惠券已经被领取");
        }
        if ($coupon_Data["wxapp_id"] != $this->wxapp_id) {
            return app("json")->fail("领取的门店错误");
        }
        $f = Db::name("store_coupon_user")->where("id", $coupon_id)->update([
            "uid" => $rev_id,
            'other_id' => $send_id
        ]);
        if ($f) {
            return app("json")->successful("优惠券领取成功");
        }
        return app("json")->successful("优惠券领取失败");
    }
}